package cs5300;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Iterator;

public class SessionTable {
	static Hashtable<String, sessionState> sessionTable = new Hashtable<String, sessionState>();
	static SessionTable st;
	static int maxSession = 1000;

	private SessionTable() {

	}

	public static SessionTable getInstance() {
		if (st == null) {
			st = new SessionTable();
		}
		return st;
	}

	/**
	 * insert a session into the hashtable
	 * 
	 * @param ss
	 * @return
	 */
	public boolean insertSession(sessionState ss) {
		if (full()) {
			clean();
			if (full()) {
				return false;
			}
		}
		sessionTable.put(ss.cookie.sessionID, ss);
		return true;
	}

	/**
	 * check if the hashtable is full or not
	 * 
	 * @return
	 */
	public boolean full() {
		return sessionTable.size() >= maxSession;
	}

	/**
	 * given a sessionID and return the State according to it
	 * 
	 * @param sessionID
	 * @return
	 */
	public sessionState getState(String sessionID) {
		sessionState ss = (sessionState) sessionTable.get(sessionID);
		return ss;
	}

	/**
	 * update the value of the seesionID
	 * 
	 * @param sessionID
	 * @param ss
	 * @return
	 */
	public boolean updateState(sessionState ss) {
		if (!sessionTable.containsKey(ss.cookie.sessionID)) {
			return false;
		}
		sessionTable.put(ss.cookie.sessionID, ss);
		return true;
	}

	/**
	 * remove a sessionID
	 * 
	 * @param key
	 * @return
	 */
	public boolean removeState(String key) {
		if (!sessionTable.containsKey(key)) {
			return false;
		}
		sessionTable.remove(key);
		return true;
	}

	/**
	 * Clean the expired session
	 */
	public void clean() {
		Iterator<sessionState> iter = sessionTable.values().iterator();
		while (iter.hasNext()) {
			//if (iter.next().expireDate > Calendar.getInstance().getTimeInMillis()) {
			//	iter.remove();
			//}
		}
	}

}
